package com.leyou.item.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import com.leyou.item.pojo.SpecGroup;
import com.leyou.item.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SpecService {
    @Autowired
    private SpecGroupMapper specGroupMapper;
    @Autowired
    private SpecParamMapper specParamMapper;

    public List<SpecGroup> findSpecGroupsByCid(Long id) {
        //1.封装条件
        QueryWrapper<SpecGroup> query = Wrappers.query();
        query.eq("cid",id);

        //2.执行查询
        List<SpecGroup> specGroups = specGroupMapper.selectList(query);

        //3.处理结果并返回
        if(CollectionUtils.isEmpty(specGroups)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return specGroups;
    }

    public List<SpecParam> findSpecParams(Long gid, Long cid, Boolean searching) {
        //1.封装条件
        QueryWrapper<SpecParam> query = Wrappers.query();
        if(gid!=null)query.eq("group_id",gid);
        if(cid!=null)query.eq("cid",cid);
        if(searching!=null)query.eq("searching",searching);

        //2.执行查询
        List<SpecParam> specParams = specParamMapper.selectList(query);

        //3.处理结果并返回
        if(CollectionUtils.isEmpty(specParams)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return specParams;
    }

    public List<SpecGroupDTO> findSpecGroupDTOsByCid(Long id) {
        //1.查询所有规格组
        List<SpecGroup> specGroups = findSpecGroupsByCid(id);
        //2.拷贝数据
        List<SpecGroupDTO> specGroupDTOS = BeanHelper.copyWithCollection(specGroups, SpecGroupDTO.class);
        //3.继续封装组里面的参数列表
        if(CollectionUtils.isNotEmpty(specGroupDTOS)){
            specGroupDTOS.forEach(specGroupDTO -> {
                //查询该组下的参数列表
                List<SpecParam> specParams = findSpecParams(specGroupDTO.getId(), null, null);
                specGroupDTO.setSpecParams(specParams);
            });
        }
        return specGroupDTOS;
    }
}
